<template>
  <div class="page">
    <div class="slot">
      <div class="top">
        <div class="return" @click="goback">
          <img src="@/assets/my/zuo.png" alt />
        </div>
        <span>购物车</span>
        <!-- <div class="bianji" @click="bianji">{{ bianjiORdel }}</div> -->
      </div>
    </div>
    <!-- <div class="agwegwa"></div> -->
    <div>
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <van-checkbox-group v-model="result" ref="checkboxGroup">
            <div
              v-for="(item, index) in dataList"
              :key="index"
              class="asdafzcv"
            >
              <van-checkbox
                :name="index"
                @click="itemCheck(item.id, index)"
                checked-color="#fdd30a"
                style="
                  padding-left: 20px;
                  padding-right: 10px;
                  background: #fafafa;
                "
              ></van-checkbox>
              <van-swipe-cell class="ssss">
                <van-card :price="item.o_price" :title="item.goods_title">
                  <template #thumb>
                    <div
                      @click="$router.push(`/shopinfo/${item.goods_id}`)"
                      class="thumb"
                    >
                      <img :src="$IP + item.goods_image" alt="" />
                    </div>
                  </template>
                  <template #desc>
                    <div
                      class="desc"
                      @click="changeguige(item.goods_id, item.id)"
                    >
                      <div class="qwe">
                        <div
                          style="
                            background-color: rgb(231, 231, 231);
                            border-radius: 5px;
                          "
                        >
                          {{ item.specs_name }}
                        </div>
                        <div class="xia">
                          <img src="../../assets/pblic/xiajt.png" alt="" />
                        </div>
                      </div>
                    </div>
                  </template>
                  <template #num>
                    <div class="totalPri">￥{{ item.o_price * item.num }}</div>
                  </template>
                  <template #footer>
                    <van-stepper
                      v-model="item.num"
                      input-width="1rem"
                      button-size="0.5rem"
                      :disable-plus="item.num===item.specs.max_num?true:false"
                      :disable-minus="item.num===item.specs.min_num?true:false"
                      disable-input
                      :min="item.specs.min_num"
                      :max="item.specs.max_num"
                      integer
                      :long-press="false"
                      @overlimit="overlimit(index)"
                      @change="numChange(index)"
                    />
                  </template>
                </van-card>
                <template #right>
                  <van-button
                    square
                    text="删除"
                    type="danger"
                    class="delete-button"
                    @click="delOrder(item.id, index)"
                  />
                </template>
              </van-swipe-cell>
            </div>
          </van-checkbox-group>
        </van-list>
      </van-pull-refresh>
    </div>
    <!-- 选规格 -->
    <div class="zhezhao" v-show="isguige" @click="isguige = false"></div>
    <!-- <div class="zhezhao2" :class="{show:isguige,hide:!hide}" > -->
    <div class="tankuang2" :class="{ show: isguige, hide: !isguige }">
      <div class="top">
        <div class="name">{{ shopinfo.title }}</div>
        <div class="guanbi" @click="guanbi">
          <img src="@/assets/home/cha.png" alt />
        </div>
      </div>
      <div class="guige" v-show="specs.length !== 0">
        <div class="p4">规格</div>
        <div class="ggbtn">
          <div
            :class="active === item.id ? 'btn1' : 'btn2'"
            @click.stop="xuanguige(item.id)"
            v-for="item in specs"
            :key="item.id"
          >
            {{ item.name }}
          </div>
        </div>
      </div>
      <div class="guige">
        <div class="p4">数量</div>
        <div class="num">
          <ul class="shuliangtianxie">
            <li class="num1">
              <div class="imgsa">
                <img
                  src="@/assets/my/sub.png"
                  @click.stop="subtract()"
                  class="subaddbt"
                />
              </div>
            </li>

            <li class="num1">
              <input
                class="input"
                @change="change($event)"
                placeholder="请输入采购数量"
                type="number"
                :min="specsinfo.min_num"
                v-model="btcount"
                oninput="if(value>99999)value=99999"
              />
            </li>
            <li class="num1">
              <div class="imgsa">
                <img
                  src="@/assets/my/plus.png"
                  @click.stop="add()"
                  class="subaddbt"
                />
              </div>
            </li>
          </ul>

          <!--cristo-->
        </div>
      </div>
      <div class="yixuan">
        <div class="span1">
          已选规格：
          <span class="span2"
            >{{ specs.length === 0 ? shopinfo.title : specsinfo.name }}
            {{ btcount === "" ? 0 : btcount }}{{ shopinfo.unit }}</span
          >
        </div>
      </div>
      <div class="zong">
        <div class="left">
          <span class="p9">
            总计
            <span class="p8">
              ￥
              <span class="p7">{{ allprice }}</span
              ><!--{{allprice}}-->
            </span>
          </span>
        </div>
        <div class="right" @click="quedin">确定</div>
      </div>
    </div>
    <!-- </div> -->
    <van-submit-bar
      :price="total_price"
      :button-text="orderBtn"
      :button-color="orderBtnbgc"
      @submit="onSubmit"
    >
      <van-checkbox checked-color="#fdd30a" v-model="checked" @click="checkAll"
        >全选</van-checkbox
      >
    </van-submit-bar>
    <div class="oargin"></div>
    <MyNavbar></MyNavbar>
  </div>
</template>
<script>
import MyNavbar from "@/components/MyNavbar";
import axios from "axios";
export default {
  name: "",
  data() {
    return {
      isguige: false, // 选规格
      token: "",
      orderBtn: "提交订单",
      orderBtnbgc: "#fdd40a",
      bianjiORdel: "编辑",
      dataList: [],
      loading: false,
      finished: false,
      refreshing: false,
      result: [],
      checked: false,
      //   value: 0,
      total_price: 0,
      cart_ids: "",
      num: 0,
      shopinfo: "",
      specs: "",
      active: NaN,
      btcount: "",
      min_num: 0,
      specsinfo: {},
      allprice: 0,
      goods_id: "",
      card_id: "",
    };
  },
  watch: {
    result: function (val, oldVal) {
      if (val !== oldVal) {
        this.total_price = 0;
        this.cart_ids = "";
        this.num = 0;
        for (let i = 0; i < val.length; i++) {
          this.total_price =
            this.total_price +
            Number(this.dataList[val[i]].o_price) *
              this.dataList[val[i]].num *
              100;
          this.num = this.num + this.dataList[val[i]].num;
          if (this.cart_ids === "") {
            this.cart_ids = this.dataList[val[i]].id;
          } else {
            this.cart_ids = this.cart_ids + "," + this.dataList[val[i]].id;
          }
        }
      }
    },
    dataList: {
      handler(val, oldVal) {
        this.total_price = 0;
        for (let i = 0; i < this.result.length; i++) {
          this.total_price =
            this.total_price +
            Number(this.dataList[this.result[i]].o_price) * this.dataList[this.result[i]].num * 100;
        }
      },
      deep: true,
    },
    btcount: function (newVal, oldVal) {
      if (this.specsinfo.o_price) {
        if (this.specs.length === 0) {
          this.allprice = newVal * this.shopinfo.price;
        } else {
          this.allprice = newVal * this.specsinfo.o_price;
        }
      } else {
        this.$toast("请选择商品规格");
      }
    },
  },
  created() {
    this.onRefresh();
    this.token = localStorage.getItem("token");
  },
  methods: {
    overlimit(index){
      console.log(this.dataList[index]);
      if(this.dataList[index].num>=this.dataList[index].specs.min_num && this.dataList[index].num<this.dataList[index].specs.max_num){
        this.$toast(`最少购买${this.dataList[index].specs.min_num}份`)
      }else{
        this.$toast(`最多购买${this.dataList[index].specs.max_num}份`)
      }
    },
    numChange(index) {
      axios
        .post(
          "/index/Cart/goodsOperate",
          this.$qs.stringify({
            token: this.token,
            goods_id: this.dataList[index].goods_id,
            num: this.dataList[index].num,
            specs_id: this.dataList[index].specs_id,
            id: this.dataList[index].id,
          })
        )
        .then((res) => {
          if (res.data.code === 1) {
            // this.onRefresh();
          } else {
            this.$toast(res.data.msg);
          }
        });
    },
    quedin() {
      this.isguige = false;
      if (this.specs.length === 0) {
        // if (this.num === 0) {
        //   this.$toast("商品数量不能为0");
        // } else {
        //   axios
        //     .post(
        //       "/index/order/add",
        //       this.$qs.stringify({
        //         token: this.token,
        //         goods_id: this.goods_id,
        //         price: this.shopinfo.price,
        //         num: this.btcount,
        //       })
        //     )
        //     .then((res) => {
        //       if (res.data.code === 1) {
        //         this.$router.push(
        //           "/confirmorder?order_id=" + res.data.data.order_id
        //         );
        //       } else {
        //         this.$toast(res.data.msg);
        //       }
        //     });
        // }
      } else {
        if (
          Object.keys(this.specsinfo).length == 0 ||
          this.btcount === 0 ||
          this.btcount == ""
        ) {
          this.$toast("请选择商品规格并填写数量");
        } else {
          axios
            .post(
              "/index/Cart/goodsOperate",
              this.$qs.stringify({
                token: this.token,
                goods_id: this.goods_id,
                num: this.btcount,
                specs_id: this.active,
                id: this.card_id,
              })
            )
            .then((res) => {
              if (res.data.code === 1) {
                this.isguige = false;
                this.$toast("修改成功");
                this.onRefresh();
              } else if (res.data.code === -10) {
                this.isshow = true;
                this.isguige = false;
              } else if (res.data.code === -1) {
                this.$toast("未登录");
                this.$router.replace("/home");
              } else {
                this.$toast(res.data.msg);
              }
            });
        }
      }
    },
    xuanguige(id) {
      this.active = id;
      var specs = this.specs;
      this.specsinfo = specs.filter((item) => item.id === id)[0];
      this.btcount = this.btcount === "" ? 1 : this.btcount;
      if (this.specs.length === 0) {
        this.allprice = this.btcount * this.shopinfo.price;
      } else {
        this.allprice = this.btcount * this.specsinfo.o_price;
      }
    },
    changeguige(id, card_id) {
      this.isguige = true;
      this.goods_id = id;
      this.card_id = card_id;
      axios
        .post(
          "/index/goods/info",
          this.$qs.stringify({
            id: id,
            token: this.token,
          })
        )
        .then((res) => {
          if (res.data.code === 1) {
            this.shopinfo = res.data.data;
            this.allprice=0
            this.specs = res.data.data.specs;
          }
        });
    },
    add(btcount) {
      if (this.specsinfo.o_price) {
        this.btcount++;
        // axios.post(
        //   "index/Cart/goodsOperate",
        //   this.$qs.stringify({
        //     goods_id, //是	int	商品id
        //     specs_id, //是	int	规格id
        //     num, //是	int	数量
        //     id, //否	int	购物车id，修改必填
        //     token: this.token,
        //   })
        // );
      } else {
        this.$toast("请选择商品规格");
      }
    },
    subtract(btcount) {
      if (this.btcount <= 1) {
        this.$toast("采购数量无法再减少");
        // this.btcount=1;
      } else {
        this.btcount -= 1;
      }
    },
    guanbi() {
      this.isguige = false;
    },
    onLoad() {
      if (this.refreshing) {
        this.refreshing = false;
      }
      if (!this.finished) {
        axios
          .post(
            "/index/Cart/index",
            this.$qs.stringify({
              token: localStorage.getItem("token"),
            })
          )
          .then((res) => {
            if (res.data.code === 1) {
              this.dataList = this.dataList.concat(res.data.data.data);
              this.loading = false;
            }
            if (this.dataList.length >= res.data.data.total) {
              this.finished = true;
            }
          });
      }
    },
    onRefresh() {
      this.dataList = [];
      // 清空列表数据
      this.finished = false;

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true;
      this.onLoad();
    },
    itemCheck(id, index) {
      // console.log(id,index)
      // console.log('result', this.result)
    },
    checkAll() {
      console.log("result", this.result);
      if (!this.checked) {
        this.$refs.checkboxGroup.toggleAll();
      } else {
        this.$refs.checkboxGroup.toggleAll(true);
      }
    },
    bianji() {
      if (this.bianjiORdel === "编辑") {
        this.orderBtn = "删除订单";
        this.orderBtnbgc = "#f01225";
        this.bianjiORdel = "取消";
      } else {
        this.orderBtn = "提交订单";
        this.orderBtnbgc = "#fdd40a";
        this.bianjiORdel = "编辑";
      }
    },
    delOrder(id, index) {
      axios
        .post(
          "/index/cart/del",
          this.$qs.stringify({
            token: localStorage.getItem("token"),
            id: id,
          })
        )
        .then((res) => {
          if (res.data.code === 1) {
            this.$toast("删除成功");
            this.dataList.splice(index, 1);
          }
        });
    },
    onSubmit() {
      if (this.bianjiORdel === "编辑") {
        if (this.result.length === 0) {
          this.$toast("请选择商品");
          return;
        }
        axios
          .post(
            "index/order/add",
            this.$qs.stringify({
              token: localStorage.getItem("token"),
              cart_ids: this.cart_ids,
              num: this.num,
              total: this.total_price / 100,
            })
          )
          .then((res) => {
            if (res.data.code === 1) {
              this.$router.push(
                `/confirmorder?order_id=${res.data.data.order_id}&cart_ids=${res.data.data.cart_ids}`
              );
            } else if (res.data.code === -2) {
              this.$toast(res.data.msg);
              this.$router.push("/settlement");
            } else if (res.data.code === -10) {
              this.$toast(res.data.msg);
            }
          });
      } else {
        console.log("删除订单", "");
      }
    },
    goback() {
      this.$router.back();
    },
  },
  components: {
    MyNavbar,
  },
};
</script>
<style lang="scss" scoped>
.page {
  position: relative;
}
.hide {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) scale(0);
  transition: all 0.4s cubic-bezier(0.6, -0.28, 0.735, 0.045);
}
.show {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) scale(1);
  transition: all 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
.desc {
  width: 100%;
  .qwe {
    width: auto !important;
    display: flex;
    justify-content: start;
    border-radius: 5px;
    margin-top: 10px;
    padding: 0 5px;
    .xia {
      margin-left: 5px;
      img {
        width: 8px;
        height: 5px;
      }
    }
  }
}

.thumb {
  height: 100%;
  width: 100%;
  img {
    height: 100%;
    width: 100%;
  }
}
.delete-button {
  height: 100%;
}
.agwegwa {
  height: 44px;
}
.oargin {
  height: 50px;
}
.profit {
  width: 100%;
  height: 100%;
  .profit_top {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 6;
    width: 100%;
    height: 44px;
    background: #fdd30a;
    font-size: 18px;
    font-family: PingFang SC;
    font-weight: bold;
    color: #323232;
    line-height: 44px;
    text-align: center;
  }
}
.asdafzcv {
  display: flex;
  justify-content: space-between;
}
.ssss {
  width: 100%;
}
.slot {
  width: 100%;
  height: 44px;
  .top {
    width: 100%;
    height: 44px;
    display: flex;
    display: -webkit-flex;
    justify-content: center;
    align-items: center;
    background: #fdd30a;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 100;
    .return {
      width: 38px;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      display: flex;
      display: -webkit-flex;
      justify-content: center;
      align-items: center;
      img {
        width: 8px;
        height: 15px;
      }
    }
    span {
      font-size: 18px;
      font-family: PingFang SC;
      font-weight: bold;
      color: #000000;
      line-height: 44px;
    }
    .bianji {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      right: 20px;
      font-size: 14px;
    }
  }
}
.zhezhao {
  width: 100vw;
  height: 100%;
  background: #000000;
  opacity: 0.5;
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  z-index: 999;
}
// .zhezhao2 {
//   width: 100%;
//   height: 100%;
//   position: fixed;
//   top: 0;
//   left: 0;
//   z-index: 900;
//   display: flex;
//   display: -webkit-flex;
//   justify-content: center;
//   align-items: center;
.tankuang2 {
  position: fixed;
  z-index: 1000;
  width: 330px;
  background: #ffffff;
  border-radius: 10px;
  .top {
    width: 100%;
    height: 49px;
    position: relative;
    text-align: center;
    .name {
      font-size: 18px;
      font-family: PingFang SC;
      font-weight: bold;
      color: #222222;
      line-height: 49px;
    }
    .guanbi {
      width: 18.5px;
      height: 18.5px;
      position: absolute;
      top: 5px;
      right: 5px;
      img {
        width: 18.5px;
        height: 18.5px;
      }
    }
  }
  .guige {
    .p4 {
      font-size: 14px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #333333;
      margin-left: 15px;
    }
    .ggbtn {
      display: flex;
      display: -webkit-flex;
      align-items: center;
      flex-wrap: wrap;
      margin-bottom: 20px;
      .btn1 {
        width: 90px;
        height: 37px;
        background: #fdd40a;
        border-radius: 18.5px;
        margin-left: 15px;
        font-size: 14px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #222222;
        line-height: 37px;
        text-align: center;
        margin-top: 10px;
        overflow: hidden;
      }
      .btn2 {
        width: 90px;
        height: 37px;
        background: #ececec;
        border-radius: 18.5px;
        margin-left: 15px;
        font-size: 14px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #555555;
        line-height: 37px;
        text-align: center;
        margin-top: 10px;
        overflow: hidden;
      }
    }
    .num {
      width: 300px;
      margin: auto;
      display: flex;
      display: -webkit-flex;
      justify-content: center;
      align-items: center;
      padding: 10px 0;
      border-bottom: 1px solid #d3d3d3;
      .input {
        width: 100%;
        border: none;
        font-size: 15px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #333333;
        line-height: 20px;
        padding: 0 10px;
        box-sizing: border-box;
      }
      .shuliangtianxie {
        .num1 {
          list-style: none;
          float: left;
          text-align: center;
          .input {
            width: 100%;
            height: 100%;
            border: none;
            font-size: 15px;
            font-family: PingFang SC;
            font-weight: 500;
            color: #333333;
            line-height: 20px;
            padding: 0 10px;
          }
          .imgsa {
            width: 26px;
            height: 26px;
          }
          .subaddbt {
            width: 100%;
            height: 100%;
          }
        }
      }
    }
  }
  .yixuan {
    width: 327px;
    height: 33px;
    margin: 22.5px 0 0 0;
    background: #f9f9f9;
    border: 1px solid #e5e5e5;
    .span1 {
      font-size: 12px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #888888;
      line-height: 33px;
      margin-left: 15px;
      .span2 {
        color: #222222;
      }
    }
  }
  .zong {
    width: 300px;
    margin: 15px;
    display: flex;
    display: -webkit-flex;
    justify-content: space-between;
    align-items: center;
    .left {
      .p9 {
        font-size: 14px;
        font-family: PingFang SC;
        font-weight: bold;
        color: #000000;
        line-height: 14px;
        .p8 {
          font-size: 12px;
          font-family: PingFang SC;
          font-weight: bold;
          color: #ff511e;
          line-height: 12px;
          .p7 {
            font-size: 18px;
            font-family: PingFang SC;
            font-weight: bold;
            color: #ff511e;
            line-height: 18px;
          }
        }
      }
    }
    .right {
      width: 90px;
      height: 40px;
      background: #fdd40a;
      border-radius: 20px;
      font-size: 14px;
      font-family: PingFang SC;
      font-weight: bold;
      color: #222222;
      line-height: 40px;
      text-align: center;
    }
  }
}
// }
</style>